const express = require('express');
let router = express.Router();
const multer = require('multer');
let mysql = require('mysql');
var sql01 = require('./../db/connction'); //连接池
// 使用DBConfig.js的配置信息创建一个MySQL连接池
let pool = mysql.createPool(sql01.mysql);
var  Global = require('./../Global');
//var iconv = require('iconv-lite');//处理文件名中文GBK乱码

let upload = multer({
  storage: multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, './public/uploadcontent'); //上传文件的保存目录
    },
    filename: function (req, file, cb) {

      

      var rancode = 100000 + parseInt(Math.random() * 900000); //6位
      var changedName = (new Date().getTime()) +'-'+rancode+ '-' + file.originalname;
     
      cb(null, changedName);
    }
    // function fileFilter (req, file, cb) {

    //   // 这个函数应该调用 `cb` 用boolean值来
    //   // 指示是否应接受该文件

    //   // 拒绝这个文件，使用`false`，像这样:
    //   cb(null, false)

    //   // 接受这个文件，使用`true`，像这样:
    //   cb(null, true)

    //   // 如果有问题，你可以总是这样发送一个错误:
    //   cb(new Error('I don\'t have a clue!'))

    // }
  })
});

//获取客户端ip
function getClientIP(req) {
  return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
    req.connection.remoteAddress || // 判断 connection 的远程 IP
    req.socket.remoteAddress || // 判断后端的 socket 的 IP
    req.connection.socket.remoteAddress;
};

//上传记录
function uploaderLog(ip,file) {
  return new Promise((resolve, reject) => {
    pool.getConnection(function (err, connection) {

      var sql = "INSERT into uploadinfo(path,originalname,size,mimetype,ip,date) VALUES(?,?,?,?,?,now()) ";
      var addParam = [file["path"].replace("\.\.","").replace("\\","/"),file["originalname"],file["size"],file["mimetype"],ip?ip:''];
      connection.query(sql,addParam, function (err, result) {
        if (err) {
          reject({
            finish: false,
            data: err.message
          });
          connection.release(); //释放连接
        } else {
          
          resolve({
            finish: true
          });
          connection.release();
        }
      });
    });
  })
}


//单个文件上传  upload.single('文件名')  对应 new FormData().append('文件名', file)
router.post('/single', upload.single('file'), async (req, res, next) => {

  console.log("req.file", req.file);

  let ip= getClientIP(req);



  // server {
  //   listen       80;
  //   server_name  localhost;
  //   charset utf-8;
  // location / {
  //   #代理本地文件夹
  //         root   D:\\nginx-1.10.2\mixin;
  //         autoindex on;
  //         index  index.html index.htm;
  //         proxy_pass http://127.0.0.1:5000/;
  //     }

  //图片浏览目录   xp99.top/imageview/a.jpg  => xp99.top/uploadcontent/a.jpg
  //app.js   => app.use('/imageview',express.static(path.join(__dirname, 'uploadcontent')));
//   let imageReplaceDir = Global.imageReplaceDir;//虚拟目录

  //只要域名，不要端口号，
  if(!!req.file["path"]){
    let patname = req.file["path"].toString();
    // patname =patname.replace(imageReplaceDir["target"],imageReplaceDir["to"]);
    patname =patname.replace(/.*uploadcontent/,"uploadcontent");
    patname =patname.replace("\.\.","");
    patname =patname.replace(/\\/g,"/");
    req.file["path"] =Global.Host+'/'+patname;
  }


  //上传的图片path 改为绝对路径（去掉前面两个..），部署到服务器后在vue项目根目录下建立uploadcontent目录，作为node上传文件接收目录。
  //将node项目移动到vue项目根目录下作为二级目录。vue展示图片时直接从数据库取
  let uploaderLogjson = await uploaderLog(ip,req.file).catch(err=>{return err});
  if(!uploaderLogjson.finish){
    res.json({
      resultCode: 400,
      message: uploaderLogjson.data
    })
  }else{
    res.json({
      resultCode: 200,
      message: '成功',
      data: {
        size: req.file.size,
        type: 'single',
        originalname: req.file.originalname,
        path: req.file.path,
        fileType: req.file.mimetype
      }
    })
  }

});

//多个文件上传
router.post('/multer', upload.array('Files'), (req, res) => {
 
  let fileList = [];
  req.files.map((elem) => {
    fileList.push({
      originalname: elem.originalname
    })
  });
  res.json({
    code: '0000',
    type: 'multer',
    fileList: fileList
  });
});

module.exports = router;